package com.bigstar.lolkor;

import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.google.ads.AdRequest;
import com.google.ads.AdView;



public class RankingBoard extends ListActivity {
	ArrayList<RankInfo> rankArray = new ArrayList<RankInfo>();
	ListAdapter adapter;
	int state = 0;
	int page = 1;
	int max_page = 1;
	AutoCompleteTextView et_search;
	String url;
	private ProgressDialog pd;
	boolean name_search = false;
	String search_name = "";
	int teamPosition;
	EditText et;
	@Override 
	public void onCreate(Bundle savedInstanceState) { 
		super.onCreate(savedInstanceState); 
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 
        ChampionData.load(this);
        ItemData.load(this);
        Rune.load(this);
		setContentView(R.layout.ranking_board); 
        AdView adview = (AdView)findViewById(R.id.adView);
        AdRequest re = new AdRequest(); 
        adview.loadAd(re);
		page = 1;
		max_page = 1;
		state = 2;
		search_name = "";
		adapter = new ListAdapter(this);
		setListAdapter(adapter);
		process("http://www.leagueoflegends.co.kr/e-sports/ladder_ranking.php?cate=32");
		et_search = (AutoCompleteTextView)findViewById(R.id.et_name);
//		setAdapter();
		RankingBoard.this.findViewById(R.id.btn_solo5x5).setBackgroundResource(R.drawable.rank_tab_ov);
		name_search = false;
		Button b = (Button)this.findViewById(R.id.btn_team3x3);
		b.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				state = 0;
				page = 1;
				max_page = 1;
				name_search = false;
				search_name = "";
				v.setBackgroundResource(R.drawable.rank_tab_ov);
				RankingBoard.this.findViewById(R.id.btn_team5x5).setBackgroundResource(R.drawable.rank_tab);
				RankingBoard.this.findViewById(R.id.btn_solo5x5).setBackgroundResource(R.drawable.rank_tab);
				((TextView)RankingBoard.this.findViewById(R.id.tv_ladder_name)).setText("Team Name");
				((TextView)RankingBoard.this.findViewById(R.id.tv_search)).setText("검색(팀이름):");
				et_search.setText("");
				process("http://www.leagueoflegends.co.kr/e-sports/ladder_ranking.php?cate=30");
			}
			
		});
		b = (Button)this.findViewById(R.id.btn_team5x5);
		b.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				state = 1;
				page = 1;
				max_page = 1;
				name_search = false;
				search_name = "";
				v.setBackgroundResource(R.drawable.rank_tab_ov);
				RankingBoard.this.findViewById(R.id.btn_team3x3).setBackgroundResource(R.drawable.rank_tab);
				RankingBoard.this.findViewById(R.id.btn_solo5x5).setBackgroundResource(R.drawable.rank_tab);
				((TextView)RankingBoard.this.findViewById(R.id.tv_ladder_name)).setText("Team Name");
				((TextView)RankingBoard.this.findViewById(R.id.tv_search)).setText("검색(팀이름):");
				et_search.setText("");
				process("http://www.leagueoflegends.co.kr/e-sports/ladder_ranking.php?cate=31");
			}
			
		});
		b = (Button)this.findViewById(R.id.btn_solo5x5);
		b.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				state = 2;
				page = 1;
				max_page = 1;
				name_search = false;
				search_name = "";
				v.setBackgroundResource(R.drawable.rank_tab_ov);
				RankingBoard.this.findViewById(R.id.btn_team3x3).setBackgroundResource(R.drawable.rank_tab);
				RankingBoard.this.findViewById(R.id.btn_team5x5).setBackgroundResource(R.drawable.rank_tab);
				((TextView)RankingBoard.this.findViewById(R.id.tv_ladder_name)).setText("Player Name");
				((TextView)RankingBoard.this.findViewById(R.id.tv_search)).setText("검색(소환사명):");
				et_search.setText("");
				process("http://www.leagueoflegends.co.kr/e-sports/ladder_ranking.php?cate=32");
			}
			
		});
		
		b = (Button)this.findViewById(R.id.rank_name_search);
		b.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				if(et_search.getText().toString().equals("")){
					if(state == 0){
						Utils.showDialog(RankingBoard.this, "LOL백과사전", "팀이름을 입력하세요.");
					}else if(state == 1){
						Utils.showDialog(RankingBoard.this, "LOL백과사전", "팀이름을 입력하세요.");
					}else if(state == 2){
						Utils.showDialog(RankingBoard.this, "LOL백과사전", "소환사명을 입력하세요.");	
					}
					return;
				}
				page = 1;
				max_page = 1;
				name_search = true;
				process("http://www.leagueoflegends.co.kr/e-sports/ladder_ranking.php?cate=3"+state+"&sortkey=&desc=desc&keyfield=USER&keyword="+URLEncoder.encode(et_search.getText().toString()));
			}
			
		});
		
		
		
		b = (Button)this.findViewById(R.id.btn_p_first);
		b.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				if(page != 1){
					page = 1;
					max_page = 1;
					String name = "";
					if(!search_name.equals("") && name_search){
						name = "&keyfield=USER&keyword="+URLEncoder.encode(search_name);
					}
					process("http://www.leagueoflegends.co.kr/e-sports/ladder_ranking.php?cate=3"+state+"&page="+page+name);
				}
			}
			
		});
		b = (Button)this.findViewById(R.id.btn_p_prev);
		b.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				if(1 < page){
					page--;
					String name = "";
					if(!search_name.equals("") && name_search){
						name = "&keyfield=USER&keyword="+URLEncoder.encode(search_name);
					}
					process("http://www.leagueoflegends.co.kr/e-sports/ladder_ranking.php?cate=3"+state+"&page="+page+name);
				}
			}
			
		});
		b = (Button)this.findViewById(R.id.rank_page_search);
		b.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				et = new EditText(RankingBoard.this);
				et.setInputType(InputType.TYPE_CLASS_NUMBER);
				new AlertDialog.Builder(RankingBoard.this)
				.setIcon(R.drawable.icon)
				.setTitle("LOL백과사전")
				.setMessage("검색할 페이지를 입력하세요.("+1+"/"+max_page+")")
				.setView(et)
				.setPositiveButton("검색", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						if(!et.getText().toString().equals("")){
							int input = 1;
							try{
								input = Integer.parseInt(et.getText().toString());
							}catch(Exception e){
								return;
							}
							if(input >= 1 && input <= max_page){
								page = input;
								String name = "";
								if(!search_name.equals("") && name_search){
									name = "&keyfield=USER&keyword="+URLEncoder.encode(search_name);
								}
								process("http://www.leagueoflegends.co.kr/e-sports/ladder_ranking.php?cate=3"+state+"&page="+page+name);	
							}
						}
					}
				})
				.setNegativeButton("닫기", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
					}
				})
				.create().show();
			}
			
		});
		b = (Button)this.findViewById(R.id.btn_p_next);
		b.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				if(page < max_page){
					page++;
					String name = "";
					if(!search_name.equals("") && name_search){
						name = "&keyfield=USER&keyword="+URLEncoder.encode(search_name);
					}
					process("http://www.leagueoflegends.co.kr/e-sports/ladder_ranking.php?cate=3"+state+"&page="+page+name);
				}
			}
			
		});
		b = (Button)this.findViewById(R.id.btn_p_last);
		b.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				if(page < max_page){
					page = max_page;
					String name = "";
					if(!search_name.equals("") && name_search){
						name = "&keyfield=USER&keyword="+URLEncoder.encode(search_name);
					}
					process("http://www.leagueoflegends.co.kr/e-sports/ladder_ranking.php?cate=3"+state+"&page="+max_page+name);
				}
			}
			
		});
	}
	
	@Override
    public void onListItemClick(ListView parent, View v, int position, long id) {
		if(state != 2){
			teamPosition = position;
			teamProcess("http://www.leagueoflegends.co.kr/e-sports/ladder_ranking_proc.php");	
		}
	}
	
	final Runnable mSaleUpdate = new Runnable() {
		public void run() {
			if(Utils.isNetwork(RankingBoard.this)){	
				process2();
			}
            new Thread(new Runnable() {
                @Override
                public void run() {    
                    runOnUiThread(new Runnable(){
                        @Override
                         public void run() {
                        	if(rankArray.size() > 0 && name_search && !et_search.getText().toString().equals("")){
                        		search_name = et_search.getText().toString();
                        	}else if(name_search){
                        		et_search.setText(search_name);
                        	}
                     //   	saveRankId();
                        	adapter.notifyDataSetChanged();
                			if (pd != null) {
                				pd.dismiss();
                				pd = null;
                			}
                		//	setAdapter();
                			((Button)RankingBoard.this.findViewById(R.id.rank_page_search)).setText("페이지 검색\r\n("+page+"/"+max_page+")");
                         }
                    });
                }
            }).start(); 
		}

	};
	ArrayList<String> team = new ArrayList<String>();
	final Runnable mTeamUpdate = new Runnable() {
		public void run() {
			if(Utils.isNetwork(RankingBoard.this)){	
				try {
					team.clear();
					String n = Utils.sendPost(url, rankArray.get(teamPosition).teamVal, teamPosition+1, 
							rankArray.get(teamPosition).name);
					n = n.substring(2, n.length()-2);
					StringTokenizer st = new StringTokenizer(n, ",");
					String temp;
					while((temp = st.nextToken()) != null){
						team.add(Utils.unescape(Utils.replaceAll(temp, "\\","%")));
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
            new Thread(new Runnable() {
                @Override
                public void run() {    
                    runOnUiThread(new Runnable(){
                        @Override
                         public void run() {
                			if (pd != null) {
                				pd.dismiss();
                				pd = null;
                			}
                			String names = "";
        					for(int i = 2; i < team.size()-3; i++){
        						names += team.get(i) + "\r\n";
        					}
                			Utils.showDialog(RankingBoard.this, rankArray.get(teamPosition).name+"의 팀원 목록", names.replaceAll("\"", ""));
                         }
                    });
                }
            }).start(); 
		}

	};
	
	public void process(String url){
		this.url = url;
		if (pd == null) {
			pd = ProgressDialog.show(this, "", "래더랭킹 정보를 받아오고 있습니다.", true);
			pd.show();
		}
		rankArray.clear();
		Thread t = new Thread(mSaleUpdate);
		t.start();
    }
	
	public void process2(){
		try {
			Source source = new Source(new URL(url));
	    	List<Element> atags = source.getAllElements(HTMLElementName.TR);
	    	RankInfo info = null;
	    	for(int i = 1; i < atags.size(); i++){		
	    		Element e = atags.get(i);
	    		info = new RankInfo();
	    		info.rank = Integer.parseInt(e.getChildElements().get(1).getTextExtractor().toString().trim());
	    		info.name = e.getChildElements().get(2).getTextExtractor().toString();
	    		if(state != 2){
		    		for(int j = 29; j < e.getChildElements().get(2).getAllElements(HTMLElementName.SPAN).get(0).toString().length(); j++){
		    			if(e.getChildElements().get(2).getAllElements(HTMLElementName.SPAN).get(0).toString().substring(j, j+1).equals(",")){
		    	    		info.teamVal = Integer.parseInt(e.getChildElements().get(2).getAllElements(HTMLElementName.SPAN).get(0).toString().substring(29, j));
		    	    		break;
		    			}
		    		}	
	    		}
	    		info.win = Integer.parseInt(e.getChildElements().get(3).getTextExtractor().toString().trim());
	    		info.losses = Integer.parseInt(e.getChildElements().get(4).getTextExtractor().toString().trim());
	    		info.rating = Integer.parseInt(e.getChildElements().get(5).getTextExtractor().toString().trim());
	    		rankArray.add(info);
	    	}
	    	int rank_index = 0;
	    	for(int i = 0; i < source.getAllElements(HTMLElementName.UL).size(); i++){	
	    		if(source.getAllElements(HTMLElementName.UL).get(i) != null){
	    			if(source.getAllElements(HTMLElementName.UL).get(i).getContent().toString().length() < 15){
	    				continue;
	    			}
	    			if(source.getAllElements(HTMLElementName.UL).get(i).getContent().toString().substring(0, 15).equals("<a href='ladder")){
		    			rank_index = i;
		    			break;
	    			}
	    		}
	    	}
    		Element e = source.getAllElements(HTMLElementName.UL).get(rank_index);
	    	for(int i = 0; i < e.getChildElements().size(); i++){		
	    		if(e.getChildElements().get(i).getAttributeValue("href") != null){
	    			int start = 0;
		    		for(int j = 0; j < e.getChildElements().get(i).getAttributeValue("href").length(); j++){
		    			if(e.getChildElements().get(i).getAttributeValue("href").substring(j, j+1).equals("=")){
		    				start = j;
		    			}
		    			if(e.getChildElements().get(i).getAttributeValue("href").substring(j, j+1).equals("&") && start != 0){
		    				max_page = Integer.parseInt(e.getChildElements().get(i).getAttributeValue("href").substring(start+1, j));
		    		    	break;
		    			}
		    		}
	    		}
	    	}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
	
	public void teamProcess(String url){
		this.url = url;
		if (pd == null) {
			pd = ProgressDialog.show(this, "", "팀 정보를 받아오고 있습니다.", true);
			pd.show();
		}
		Thread t = new Thread(mTeamUpdate);
		t.start();
    }
	
	
	
	class RankInfo{
		int rank;
		String name;
		int win;
		int losses;
		int rating;
		int teamVal;
	}
	
	class ListAdapter extends BaseAdapter{
		
		private Context context;
		private LayoutInflater inflater;
		
		public ListAdapter(Context context) {
			this.context = context;
			inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public int getCount() {
			return rankArray.size();
		}

		@Override
		public Object getItem(int position) {
			return rankArray.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if(convertView == null){
				convertView = inflater.inflate(R.layout.ranking_board_row, parent, false);
			}
			RankInfo info = rankArray.get(position);
			if(info != null){
				TextView tv = (TextView)convertView.findViewById(R.id.tv_rank);
				tv.setText(""+info.rank);
				tv = (TextView)convertView.findViewById(R.id.tv_ladder_name);
				tv.setText(""+info.name);
				tv = (TextView)convertView.findViewById(R.id.tv_win);
				tv.setText(""+info.win);
				tv = (TextView)convertView.findViewById(R.id.tv_losses);
				tv.setText(""+info.losses);
				tv = (TextView)convertView.findViewById(R.id.tv_rating);
				tv.setText(""+info.rating);	
			}else{
				TextView tv = (TextView)convertView.findViewById(R.id.tv_rank);
				tv.setText("");
				tv = (TextView)convertView.findViewById(R.id.tv_ladder_name);
				tv.setText("");
				tv = (TextView)convertView.findViewById(R.id.tv_win);
				tv.setText("");
				tv = (TextView)convertView.findViewById(R.id.tv_losses);
				tv.setText("");
				tv = (TextView)convertView.findViewById(R.id.tv_rating);
				tv.setText("");	
			}
			return convertView;
		}
		
	}
	
	public void saveRankId(){
		if(url.equals("http://www.leagueoflegends.co.kr/e-sports/ladder_ranking.php?cate=30") ||
				url.equals("http://www.leagueoflegends.co.kr/e-sports/ladder_ranking.php?cate=31") ||
				url.equals("http://www.leagueoflegends.co.kr/e-sports/ladder_ranking.php?cate=32")){
			return;
		}
		if(rankArray.size() > 0){
			SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
			SharedPreferences.Editor editor = pref.edit();
			for(int i = 0; i < 100; i++){
				String saveName = "";
				if(state == 0){
					saveName = "team_id_"+i;
				}else if(state == 1){
					saveName = "team_id_"+i;
				}else if(state == 2){
					saveName = "rank_id_"+i;
				}
				if(pref.getString(saveName, "").equals("")){
					editor.putString(saveName, et_search.getText().toString());
					break;
				}else if(pref.getString(saveName, "").equals(et_search.getText().toString())){
					break;
				}
			}
			editor.commit();	
		}
	}
	
	public void setAdapter(){
		if(url.equals("http://www.leagueoflegends.co.kr/e-sports/ladder_ranking.php?cate=30") ||
				url.equals("http://www.leagueoflegends.co.kr/e-sports/ladder_ranking.php?cate=31") ||
				url.equals("http://www.leagueoflegends.co.kr/e-sports/ladder_ranking.php?cate=32")){
			return;
		}
		int size = 0;
		String saveName = "";
		if(state == 0){
			saveName = "team_id_";
		}else if(state == 1){
			saveName = "team_id_";
		}else if(state == 2){
			saveName = "rank_id_";
		}
		SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
		while(!pref.getString(saveName+size, "").equals("")){
			size++;
		}
		String names[] = new String[size];
		for(int i = 0; i < size; i++){
			names[i] = pref.getString(saveName+i, "");
		}
		et_search = (AutoCompleteTextView)findViewById(R.id.et_name);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(
				this, android.R.layout.simple_dropdown_item_1line, names);
		et_search.setAdapter(adapter);
	}
}
